package keter.combofs.adapters;

import com.google.common.io.Files;
import keter.combofs.core.ComboFs;
import keter.combofs.core.impl.ComboFsImpl;
import keter.combofs.model.ComboFile;
import keter.combofs.path.PathMaker;
import keter.combofs.persist.ComboFileDao;
import keter.combofs.util.IOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 默认文件系统系统存储
 * Created by gulx@neusoft.com on 2019/11/11.
 */
public abstract  class FSAdapter implements ComboFs {

    private static final Logger logger = LoggerFactory.getLogger(ComboFsImpl.class);

    @Value("${combofs.root}")
    protected String root;

    @Autowired private PathMaker pathMaker;
    @Autowired private ComboFileDao comboFileDao;

    @Override
    public ComboFile getComboFile(Long id) throws IOException {
        ComboFile comboFile = comboFileDao.find(id);
        comboFile.setFileBytes(Files.asByteSource(new File(root+comboFile.getPath()+comboFile.getId())).read());
        return comboFile;
    }

    @Override
    public byte[] getBytes(Long id) throws IOException {
        return Files.asByteSource(new File(root+pathMaker.getPathById(id)+id)).read();
    }

    @Override
    public ComboFile save(byte[] b) throws IOException {
        Long id = sequence.nextId();
        // 不提供文件名时，文件名称与id一致
        return save(id, b, id.toString());
    }

    @Override
    public ComboFile save(byte[] b, String fileName) throws IOException {
        Long id = sequence.nextId();
        return save(id, b, fileName);
    }

    @Override
    public ComboFile save(byte[] b, String fileName, Map fileMeta) throws IOException {
        Long id = sequence.nextId();
        return save(id, b, fileName, fileMeta);
    }

    private ComboFile save(long id, byte[] b, String fileName) throws IOException {
        String path = writeFile(b, id);
        ComboFile comboFile = ComboFile.build(id, fileName, path);
        // 持久化
        comboFileDao.save(comboFile);
        return comboFile;
    }

    private ComboFile save(long id, byte[] b, String fileName, Map fileMeta) throws IOException {
        String path = writeFile(b, id);
        ComboFile comboFile = ComboFile.build(id, fileName, path, fileMeta, null);
        // 持久化
        comboFileDao.save(comboFile);
        return comboFile;
    }

    /**
     * 写入文件
     * @param b
     * @param id
     * @return
     * @throws IOException
     */
    private String writeFile(byte[] b, Long id) throws IOException {
        // 计算文件路径
        String path = pathMaker.makePath(id.toString());
        String folder = root + path;
        // 创建子目录
        IOUtil.ensureExists(folder);
        // 文件写入
        Files.write(b, new File(folder+id.toString()));
        return path;
    }

}
